import React, { useState, useEffect } from 'react';
import { userService } from '@my-workspace/shared';
import type { User, UserQueryParams, CreateUserRequest, UpdateUserRequest } from '@my-workspace/shared';

const UserManagement: React.FC = () => {
  // 状态管理
  const [users, setUsers] = useState<User[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [selectedStatus, setSelectedStatus] = useState<string>('');
  const [selectedRole, setSelectedRole] = useState<string>('');
  const [sortBy, setSortBy] = useState<keyof User>('createdAt');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
  
  // 模态框状态
  const [showAddModal, setShowAddModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [selectedUserIds, setSelectedUserIds] = useState<string[]>([]);
  const [showBatchDeleteModal, setShowBatchDeleteModal] = useState(false);
  
  // 表单状态
  const [formData, setFormData] = useState<{
    username: string;
    email: string;
    name: string;
    password: string;
    role: 'admin' | 'user' | 'guest';
    status: 'active' | 'inactive';
    department: string;
  }>({
    username: '',
    email: '',
    name: '',
    password: '',
    role: 'user',
    status: 'active',
    department: '',
  });

  // 加载用户数据
  const loadUsers = async (refresh: boolean = false) => {
    if (refresh) {
      setCurrentPage(1);
    }

    setLoading(true);
    try {
      const params: UserQueryParams = {
        page: currentPage,
        pageSize,
        keyword: searchKeyword,
        status: selectedStatus ? (selectedStatus as any) : undefined,
        role: selectedRole ? (selectedRole as any) : undefined,
        sortBy,
        sortOrder,
      };

      const response = await userService.getUsers(params);
      
      if (response.success) {
        setUsers(response.data.list || []);
        setTotal(response.data.total || 0);
      } else {
        alert('获取用户列表失败: ' + response.message);
      }
    } catch (error) {
      console.error('加载用户失败:', error);
      alert('加载用户失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载数据
  useEffect(() => {
    loadUsers();
  }, [currentPage, pageSize, searchKeyword, selectedStatus, selectedRole, sortBy, sortOrder]);

  // 处理添加用户
  const handleAddUser = async () => {
    setLoading(true);
    try {
      const request: CreateUserRequest = {
        username: formData.username,
        email: formData.email,
        name: formData.name,
        password: formData.password,
        role: formData.role,
        status: formData.status,
        department: formData.department,
      };

      const response = await userService.createUser(request);
      
      if (response.success) {
        alert('添加用户成功');
        setShowAddModal(false);
        resetForm();
        loadUsers();
      } else {
        alert('添加用户失败: ' + response.message);
      }
    } catch (error) {
      console.error('添加用户失败:', error);
      alert('添加用户失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 处理编辑用户
  const handleEditUser = async () => {
    if (!currentUser) return;

    setLoading(true);
    try {
      const request: UpdateUserRequest = {
        username: formData.username,
        email: formData.email,
        name: formData.name,
        role: formData.role,
        status: formData.status,
        department: formData.department,
      };

      const response = await userService.updateUser(currentUser.id, request);
      
      if (response.success) {
        alert('更新用户成功');
        setShowEditModal(false);
        setCurrentUser(null);
        loadUsers();
      } else {
        alert('更新用户失败: ' + response.message);
      }
    } catch (error) {
      console.error('更新用户失败:', error);
      alert('更新用户失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 处理删除用户
  const handleDeleteUser = async () => {
    if (!currentUser) return;

    setLoading(true);
    try {
      const response = await userService.deleteUser(currentUser.id);
      
      if (response.success) {
        alert('删除用户成功');
        setShowDeleteModal(false);
        setCurrentUser(null);
        loadUsers();
      } else {
        alert('删除用户失败: ' + response.message);
      }
    } catch (error) {
      console.error('删除用户失败:', error);
      alert('删除用户失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 处理批量删除
  const handleBatchDelete = async () => {
    if (selectedUserIds.length === 0) {
      alert('请选择要删除的用户');
      return;
    }

    setLoading(true);
    try {
      const response = await userService.deleteUsers(selectedUserIds);
      
      if (response.success) {
        alert(`成功删除 ${response.data.deletedCount} 个用户`);
        setShowBatchDeleteModal(false);
        setSelectedUserIds([]);
        loadUsers();
      } else {
        alert('批量删除失败: ' + response.message);
      }
    } catch (error) {
      console.error('批量删除失败:', error);
      alert('批量删除失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 打开编辑模态框
  const openEditModal = (user: User) => {
    setCurrentUser(user);
    setFormData({
      username: user.username,
      email: user.email,
      name: user.name,
      password: '', // 不显示密码
      role: user.role,
      status: user.status === 'blocked' ? 'inactive' : user.status,
      department: user.department || '',
    });
    setShowEditModal(true);
  };

  // 打开删除模态框
  const openDeleteModal = (user: User) => {
    setCurrentUser(user);
    setShowDeleteModal(true);
  };

  // 重置表单
  const resetForm = () => {
    setFormData({
      username: '',
      email: '',
      name: '',
      password: '',
      role: 'user',
      status: 'active',
      department: '',
    });
  };

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value,
    }));
  };

  // 处理排序
  const handleSort = (field: keyof User) => {
    if (sortBy === field) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      setSortBy(field);
      setSortOrder('asc');
    }
  };

  // 处理选择用户
  const handleSelectUser = (id: string) => {
    setSelectedUserIds(prev =>
      prev.includes(id) 
        ? prev.filter(userId => userId !== id)
        : [...prev, id]
    );
  };

  // 全选/取消全选
  const handleSelectAll = () => {
    if (selectedUserIds.length === users.length) {
      setSelectedUserIds([]);
    } else {
      setSelectedUserIds(users.map(user => user.id));
    }
  };

  // 渲染状态标签
  const renderStatusLabel = (status: string) => {
    const statusMap = {
      active: { label: '活跃', color: 'green' },
      inactive: { label: '禁用', color: 'gray' },
      blocked: { label: '封禁', color: 'red' },
    };

    const statusInfo = statusMap[status as keyof typeof statusMap] || { label: status, color: 'blue' };

    return (
      <span className={`inline-block px-2 py-1 text-xs rounded-full bg-${statusInfo.color}-100 text-${statusInfo.color}-800`}>
        {statusInfo.label}
      </span>
    );
  };

  // 渲染角色标签
  const renderRoleLabel = (role: string) => {
    const roleMap = {
      admin: { label: '管理员', color: 'purple' },
      user: { label: '普通用户', color: 'blue' },
      guest: { label: '访客', color: 'yellow' },
    };

    const roleInfo = roleMap[role as keyof typeof roleMap] || { label: role, color: 'gray' };

    return (
      <span className={`inline-block px-2 py-1 text-xs rounded-full bg-${roleInfo.color}-100 text-${roleInfo.color}-800`}>
        {roleInfo.label}
      </span>
    );
  };
  
  // 渲染部门标签
  const renderDepartmentLabel = (department: string) => {
    switch (department) {
      case 'marketing':
        return '市场部';
      case 'administration':
        return '行政部门';
      case 'chinese':
        return '语文组';
      case 'math':
        return '数学组';
      case 'english':
        return '英语组';
      case 'science':
        return '科学组';
      case 'humanities':
        return '人文组';
      default:
        return '-';
    }
  };

  return (
    <div className="p-4">
      <div className="mb-4">
        <h1 className="text-2xl font-bold mb-4">用户管理</h1>
        
        {/* 搜索和筛选区域 */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-4">
          <div>
            <input
              type="text"
              placeholder="搜索用户名/邮箱/姓名"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              value={searchKeyword}
              onChange={(e) => setSearchKeyword(e.target.value)}
            />
          </div>
          <div>
            <select
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              value={selectedStatus}
              onChange={(e) => setSelectedStatus(e.target.value)}
            >
              <option value="">所有状态</option>
              <option value="active">活跃</option>
              <option value="inactive">禁用</option>
              <option value="blocked">封禁</option>
            </select>
          </div>
          <div>
            <select
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              value={selectedRole}
              onChange={(e) => setSelectedRole(e.target.value)}
            >
              <option value="">所有角色</option>
              <option value="admin">管理员</option>
              <option value="user">普通用户</option>
              <option value="guest">访客</option>
            </select>
          </div>
          <div className="flex space-x-2">
            <button
              className="flex-1 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
              onClick={() => setShowAddModal(true)}
            >
              添加用户
            </button>
            {selectedUserIds.length > 0 && (
              <button
                className="flex-1 px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-red-500"
                onClick={() => setShowBatchDeleteModal(true)}
              >
                批量删除
              </button>
            )}
          </div>
        </div>

        {/* 用户列表 */}
        <div className="overflow-x-auto">
          <table className="min-w-full bg-white border border-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="py-2 px-4 border-b text-left">
                  <input
                    type="checkbox"
                    checked={users.length > 0 && selectedUserIds.length === users.length}
                    onChange={handleSelectAll}
                  />
                </th>
                <th 
                  className="py-2 px-4 border-b text-left cursor-pointer"
                  onClick={() => handleSort('username')}
                >
                  用户名 {sortBy === 'username' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th 
                  className="py-2 px-4 border-b text-left cursor-pointer"
                  onClick={() => handleSort('email')}
                >
                  邮箱 {sortBy === 'email' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th className="py-2 px-4 border-b text-left cursor-pointer"
                  onClick={() => handleSort('name')}
                >
                  姓名 {sortBy === 'name' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th className="py-2 px-4 border-b text-left">角色</th>
                <th className="py-2 px-4 border-b text-left">部门</th>
                <th className="py-2 px-4 border-b text-left">状态</th>
                <th 
                  className="py-2 px-4 border-b text-left cursor-pointer"
                  onClick={() => handleSort('createdAt')}
                >
                  创建时间 {sortBy === 'createdAt' && (sortOrder === 'asc' ? '↑' : '↓')}
                </th>
                <th className="py-2 px-4 border-b text-center">操作</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr>
                  <td colSpan={8} className="py-4 text-center">加载中...</td>
                </tr>
              ) : users.length === 0 ? (
                <tr>
                  <td colSpan={8} className="py-4 text-center">暂无用户数据</td>
                </tr>
              ) : (
                users.map(user => (
                  <tr key={user.id} className="hover:bg-gray-50">
                    <td className="py-2 px-4 border-b">
                      <input
                        type="checkbox"
                        checked={selectedUserIds.includes(user.id)}
                        onChange={() => handleSelectUser(user.id)}
                      />
                    </td>
                    <td className="py-2 px-4 border-b">{user.username}</td>
                    <td className="py-2 px-4 border-b">{user.email}</td>
                    <td className="py-2 px-4 border-b">{user.name}</td>
                    <td className="py-2 px-4 border-b">{renderRoleLabel(user.role)}</td>
                    <td className="py-2 px-4 border-b">{renderDepartmentLabel(user.department)}</td>
                    <td className="py-2 px-4 border-b">{renderStatusLabel(user.status)}</td>
                    <td className="py-2 px-4 border-b">{new Date(user.createdAt).toLocaleString()}</td>
                    <td className="py-2 px-4 border-b text-center">
                      <button
                        className="px-2 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 mr-2"
                        onClick={() => openEditModal(user)}
                      >
                        编辑
                      </button>
                      <button
                        className="px-2 py-1 text-sm bg-red-600 text-white rounded hover:bg-red-700"
                        onClick={() => openDeleteModal(user)}
                      >
                        删除
                      </button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* 分页 */}
        <div className="mt-4 flex justify-between items-center">
          <div className="text-sm text-gray-600">
            共 {total} 条记录，第 {currentPage} / {Math.ceil(total / pageSize)} 页
          </div>
          <div className="flex space-x-2">
            <select
              className="px-2 py-1 border border-gray-300 rounded"
              value={pageSize}
              onChange={(e) => setPageSize(Number(e.target.value))}
            >
              <option value={10}>10条/页</option>
              <option value={20}>20条/页</option>
              <option value={50}>50条/页</option>
            </select>
            <button
              className="px-3 py-1 border border-gray-300 rounded hover:bg-gray-100 disabled:opacity-50"
              onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
              disabled={currentPage === 1}
            >
              上一页
            </button>
            <button
              className="px-3 py-1 border border-gray-300 rounded hover:bg-gray-100 disabled:opacity-50"
              onClick={() => setCurrentPage(prev => Math.min(prev + 1, Math.ceil(total / pageSize)))}
              disabled={currentPage === Math.ceil(total / pageSize) || total === 0}
            >
              下一页
            </button>
          </div>
        </div>
      </div>

      {/* 添加用户模态框 */}
      {showAddModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-lg w-full max-w-md p-6">
            <h2 className="text-xl font-bold mb-4">添加用户</h2>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                <input
                  type="text"
                  name="username"
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  value={formData.username}
                  onChange={handleInputChange}
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                <input
                  type="email"
                  name="email"
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  value={formData.email}
                  onChange={handleInputChange}
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                <input
                  type="text"
                  name="name"
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  value={formData.name}
                  onChange={handleInputChange}
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">密码</label>
                <input
                  type="password"
                  name="password"
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  value={formData.password}
                  onChange={handleInputChange}
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">角色</label>
                <select
                  name="role"
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  value={formData.role}
                  onChange={handleInputChange}
                >
                  <option value="admin">管理员</option>
                  <option value="user">普通用户</option>
                  <option value="guest">访客</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">部门</label>
                <select
                  name="department"
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  value={formData.department}
                  onChange={handleInputChange}
                >
                  <option value="">请选择部门</option>
                  <option value="marketing">市场部</option>
                  <option value="administration">行政部门</option>
                  <option value="chinese">语文组</option>
                  <option value="math">数学组</option>
                  <option value="english">英语组</option>
                  <option value="science">科学组</option>
                  <option value="humanities">人文组</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">状态</label>
                <select
                  name="status"
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  value={formData.status}
                  onChange={handleInputChange}
                >
                  <option value="active">活跃</option>
                  <option value="inactive">禁用</option>
                </select>
              </div>
            </div>
            <div className="mt-6 flex justify-end space-x-3">
              <button
                className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-100"
                onClick={() => {
                  setShowAddModal(false);
                  resetForm();
                }}
              >
                取消
              </button>
              <button
                className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
                onClick={handleAddUser}
                disabled={loading}
              >
                {loading ? '保存中...' : '保存'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 编辑用户模态框 */}
      {showEditModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-lg w-full max-w-md p-6">
            <h2 className="text-xl font-bold mb-4">编辑用户</h2>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">用户名</label>
                <input
                  type="text"
                  name="username"
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  value={formData.username}
                  onChange={handleInputChange}
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                <input
                  type="email"
                  name="email"
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  value={formData.email}
                  onChange={handleInputChange}
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                <input
                  type="text"
                  name="name"
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  value={formData.name}
                  onChange={handleInputChange}
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">密码（留空不修改）</label>
                <input
                  type="password"
                  name="password"
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  value={formData.password}
                  onChange={handleInputChange}
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">角色</label>
                <select
                  name="role"
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  value={formData.role}
                  onChange={handleInputChange}
                >
                  <option value="admin">管理员</option>
                  <option value="user">普通用户</option>
                  <option value="guest">访客</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">状态</label>
                <select
                  name="status"
                  className="w-full px-3 py-2 border border-gray-300 rounded-md"
                  value={formData.status}
                  onChange={handleInputChange}
                >
                  <option value="active">活跃</option>
                  <option value="inactive">禁用</option>
                  <option value="blocked">封禁</option>
                </select>
              </div>
            </div>
            <div className="mt-6 flex justify-end space-x-3">
              <button
                className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-100"
                onClick={() => {
                  setShowEditModal(false);
                  setCurrentUser(null);
                }}
              >
                取消
              </button>
              <button
                className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
                onClick={handleEditUser}
                disabled={loading}
              >
                {loading ? '更新中...' : '更新'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 删除用户模态框 */}
      {showDeleteModal && currentUser && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-lg w-full max-w-md p-6">
            <h2 className="text-xl font-bold mb-4">确认删除</h2>
            <p>您确定要删除用户 "{currentUser.name}" 吗？此操作无法撤销。</p>
            <div className="mt-6 flex justify-end space-x-3">
              <button
                className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-100"
                onClick={() => {
                  setShowDeleteModal(false);
                  setCurrentUser(null);
                }}
              >
                取消
              </button>
              <button
                className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
                onClick={handleDeleteUser}
                disabled={loading}
              >
                {loading ? '删除中...' : '确认删除'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 批量删除模态框 */}
      {showBatchDeleteModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-lg shadow-lg w-full max-w-md p-6">
            <h2 className="text-xl font-bold mb-4">确认批量删除</h2>
            <p>您确定要删除选中的 {selectedUserIds.length} 个用户吗？此操作无法撤销。</p>
            <div className="mt-6 flex justify-end space-x-3">
              <button
                className="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-100"
                onClick={() => setShowBatchDeleteModal(false)}
              >
                取消
              </button>
              <button
                className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700"
                onClick={handleBatchDelete}
                disabled={loading}
              >
                {loading ? '删除中...' : '确认删除'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default UserManagement;